package com.ts.api.http.platform.biz;

import com.alibaba.fastjson.JSONObject;
import com.gitee.apanlh.util.algorithm.encrypt.symmetric.AES;
import com.gitee.apanlh.util.base.ChooseEq;
import com.gitee.apanlh.util.base.Eq;
import com.gitee.apanlh.util.base.MapUtils;
import com.gitee.apanlh.util.dataformat.JsonUtils;
import com.gitee.apanlh.util.valid.ValidParam;
import com.gitee.apanlh.web.model.vo.RequestVO;
import com.ts.api.http.platform.entity.apply.ApiPlatApplySuiXiangYong;
import com.ts.api.http.platform.entity.dataexchange.ApiPlatDataExchangeSuiXiangYong;
import com.ts.api.module.api.convert.core.annotation.ApiPlan;
import com.ts.api.module.api.convert.core.annotation.ApiPlanConvertType;
import com.ts.api.module.api.convert.core.entity.ApiApplyParameter;
import com.ts.api.module.api.convert.core.entity.ApiBizStatus;
import com.ts.api.module.api.convert.core.entity.ApiDataExchangeParameter;
import com.ts.api.module.api.convert.core.utils.ApiFieldConverter;
import com.ts.api.module.api.convert.platform.entity.RespPlatformNoticeApply;
import com.ts.api.module.api.convert.platform.entity.RespPlatformPhoneMd5Apply;
import com.ts.api.module.api.convert.platform.entity.RespPlatformPhoneMd5DataExchange;
import com.ts.api.module.api.convert.platform.handler.ApiPlatformPhoneMd5ConvertHandler;

import java.math.BigDecimal;
import java.util.Map;

/**
 *  JP4安心出&融点通-MD5信息流代投
 *  采量文档-全流程md5
 *  全量表单接口：https://ecntbybekp8t.feishu.cn/docx/KTwsd4dXkoFiUuxjytVcj2MlnPd?from=from_copylink
 * @author 江小游
 */
@ApiPlan(productId = "47", type = ApiPlanConvertType.PLAT_PHONE_MD5)
public class ApiPlatSuiXiangYongPhoneMd5Convert implements ApiPlatformPhoneMd5ConvertHandler {
    private static final String CHANNEL = "80154039";
    private static final String KEY = "D6nF9JKgHOxgaCyT";

    @Override
    public Object dataExchange(ApiDataExchangeParameter apiDataExchangeParameter) throws Exception {
        ApiPlatDataExchangeSuiXiangYong data = new ApiPlatDataExchangeSuiXiangYong();
        //  手机号
        data.setPhonemd5(apiDataExchangeParameter.getPhoneMd5());
        AES aes = AES.createEcb(KEY.getBytes());
        String dataStr = aes.encryptToBase64Str(JsonUtils.toJson(data));

        Map<String, Object> map = MapUtils.newHashMap(newMap -> {
            newMap.put("channel", CHANNEL);
            newMap.put("timestamp", System.currentTimeMillis());
            newMap.put("bizParam", dataStr);
        });
        return JsonUtils.toJson(map);
    }


    @Override
    public Object apply(ApiApplyParameter apiApplyParameter) throws Exception {
        ApiPlatApplySuiXiangYong data = new ApiPlatApplySuiXiangYong();
        ApiFieldConverter apiFieldConverter = ApiFieldConverter.create(apiApplyParameter);
        // 撞库id
        data.setOrder_sn(apiApplyParameter.dataExchangeApplyId());
        // 手机号
        data.setPhone(apiApplyParameter.getPhone());
        //  年龄
        data.setAge(apiFieldConverter.getAgeInt());
        //  性别 1男 2女
        Integer sex = ChooseEq.create()
                .when(apiApplyParameter.getSex(), "1", 2)
                .when(apiApplyParameter.getSex(), "0", 1)
                .end(1);
        data.setSex(sex);
        // 省
        data.setProvince(apiApplyParameter.getProvinceName());
        //  城市名称
        data.setCity(apiApplyParameter.getCity().replace("地区", "").replace("市", ""));
        // 姓名
        data.setName(apiApplyParameter.getUserName());
        // 贷款金额
        data.setLoan(apiFieldConverter.getLoanAmountInt());
        // 贷款期限
        //1：3个月
        //2：6个月
        //3：12个月
        //4：两年
        //5：三年
        //6：三年以上
        Integer loan = ChooseEq.create()
                .when(apiApplyParameter.getLoanTerm(), "1", 1)
                .when(apiApplyParameter.getLoanTerm(), "2", 2)
                .when(apiApplyParameter.getLoanTerm(), "3", 3)
                .when(apiApplyParameter.getLoanTerm(), "4", 4)
                .when(apiApplyParameter.getLoanTerm(), "5", 5)
                .when(apiApplyParameter.getLoanTerm(), "6", 6)
                .end(1);
        data.setLoan_term(loan);
        //贷款用途：
        //  1：购房
        //  2：购车
        //  3：住房装修
        //  4：教育深造
        //  5：休闲旅游
        //  6：个人消费
        //  7：房租缴纳
        //  8：其他贷款
        Integer loanPurpose = ChooseEq.create()
                .when(apiApplyParameter.getLoanPurpose(), "1", 5)
                .when(apiApplyParameter.getLoanPurpose(), "2", 4)
                .when(apiApplyParameter.getLoanPurpose(), "3", 8)
                .when(apiApplyParameter.getLoanPurpose(), "4", 3)
                .when(apiApplyParameter.getLoanPurpose(), "5", 8)
                .when(apiApplyParameter.getLoanPurpose(), "6", 6)
                .end(1);
        data.setLoan_use(loanPurpose);
        //  芝麻分 芝麻分：
        //1：无
        //2：600分以下
        //3：600-650分
        //4：650-700分
        //5：大于700
        Integer zhiMa = ChooseEq.create()
                .when(apiApplyParameter.getSesameCredit(), "1", 2)
                .when(apiApplyParameter.getSesameCredit(), "2", 3)
                .when(apiApplyParameter.getSesameCredit(), "3", 4)
                .when(apiApplyParameter.getSesameCredit(), "4", 5)
                .end(2);
        data.setZhima(zhiMa);
        // 是否有企业 默认值
        data.setCompany(1);
        // 花呗：
        //1：无
        //2：5000以下
        //3: 5000以上
        String btLimit = apiApplyParameter.getBtLimit();
        if (ValidParam.isNotEmpty(btLimit)) {
            Integer value = ChooseEq.create()
                    .when(apiApplyParameter.getBtLimit(), "1", 1)
                    .when(apiApplyParameter.getBtLimit(), "2", 2)
                    .when(apiApplyParameter.getBtLimit(), "3", 3)
                    .when(apiApplyParameter.getBtLimit(), "4", 3)
                    .when(apiApplyParameter.getBtLimit(), "5", 3)
                    .end(1);
            data.setBaitiao(value);
        }
        // 花呗：
        //1：无
        //2：5000以下
        //3: 5000-10000
        //4: 10000以上
        String hbLimit = apiApplyParameter.getHbLimit();
        if (ValidParam.isNotEmpty(hbLimit)) {
            Integer value = ChooseEq.create()
                    .when(hbLimit, "1", 1)
                    .when(hbLimit, "2", 2)
                    .when(hbLimit, "3", 3)
                    .when(hbLimit, "4", 4)
                    .when(hbLimit, "5", 4)
                    .end(1);
            data.setHuabei(value);
        }
        // 微粒贷
        data.setMicro_loan(1);
        //  公积金
        Integer providentFund = ChooseEq.create()
                .when(apiApplyParameter.getProvidentFund(), "1", 1)
                .when(apiApplyParameter.getProvidentFund(), "2", 2)
                .when(apiApplyParameter.getProvidentFund(), "3", 2)
                .when(apiApplyParameter.getProvidentFund(), "4", 2)
                .end(1);
        data.setFund(providentFund);
        //  社保
        Integer socialSecurity = ChooseEq.create()
                .when(apiApplyParameter.getSocialSecurity(), "1", 1)
                .when(apiApplyParameter.getSocialSecurity(), "2", 2)
                .when(apiApplyParameter.getSocialSecurity(), "3", 2)
                .when(apiApplyParameter.getSocialSecurity(), "4", 2)
                .end(1);
        data.setHas(socialSecurity);
        //  房产
        Integer house = ChooseEq.create()
                .when(apiApplyParameter.getRealEstateInfo(), "1", 1)
                .when(apiApplyParameter.getRealEstateInfo(), "2", 2)
                .when(apiApplyParameter.getRealEstateInfo(), "3", 2)
                .when(apiApplyParameter.getRealEstateInfo(), "4", 2)
                .when(apiApplyParameter.getRealEstateInfo(), "5", 2)
                .when(apiApplyParameter.getRealEstateInfo(), "6", 2)
                .end(1);
        data.setHouse(house);
        if (house != 1) {
            String houseP = ChooseEq.create()
                    .when(apiApplyParameter.getRealEstateInfo(), "2", "有房不抵押")
                    .when(apiApplyParameter.getRealEstateInfo(), "3", "有房可抵押")
                    .when(apiApplyParameter.getRealEstateInfo(), "4", "有房产")
                    .when(apiApplyParameter.getRealEstateInfo(), "5", "有按揭房产")
                    .when(apiApplyParameter.getRealEstateInfo(), "6", "有全款房产")
                    .end("有房产");
            data.setHouse_p_type(houseP);
        }
        //  车产
        Integer vehicle = ChooseEq.create()
                .when(apiApplyParameter.getCarInfo(), "1", 1)
                .when(apiApplyParameter.getCarInfo(), "2", 2)
                .when(apiApplyParameter.getCarInfo(), "3", 2)
                .when(apiApplyParameter.getCarInfo(), "4", 2)
                .end(1);
        data.setCar(vehicle);
        if (vehicle != 1) {
            String carP = ChooseEq.create()
                    .when(apiApplyParameter.getRealEstateInfo(), "2", "有车不抵押")
                    .when(apiApplyParameter.getRealEstateInfo(), "3", "有车可抵押")
                    .when(apiApplyParameter.getRealEstateInfo(), "4", "有车产")
                    .end("有车产");
            data.setCar_p_type(carP);
        }
        //  商业保险
        Integer commericalInsurance = ChooseEq.create()
                .when(apiApplyParameter.getInsurancePolicy(), "1", 1)
                .when(apiApplyParameter.getInsurancePolicy(), "2", 2)
                .when(apiApplyParameter.getInsurancePolicy(), "3", 2)
                .when(apiApplyParameter.getInsurancePolicy(), "4", 2)
                .end(1);
        data.setInsurance(commericalInsurance);
        //  信用情况
        Integer overdue = ChooseEq.create()
                .when(apiApplyParameter.getOverdue(), "1", 1)
                .when(apiApplyParameter.getOverdue(), "2", 2)
                .when(apiApplyParameter.getOverdue(), "3", 2)
                .end(1);
        data.setOverdue(overdue);
        //  学历
        //1：初中及以下
        //2：中专
        //3：高中
        //4：大专
        //5：本科
        //6：研究生及以上
        Integer education = ChooseEq.create()
                .when(apiApplyParameter.getEducationAttainment(), "1", 1)
                .when(apiApplyParameter.getEducationAttainment(), "2", 2)
                .when(apiApplyParameter.getEducationAttainment(), "3", 3)
                .when(apiApplyParameter.getEducationAttainment(), "4", 4)
                .when(apiApplyParameter.getEducationAttainment(), "5", 5)
                .when(apiApplyParameter.getEducationAttainment(), "6", 6)
                .end(2);
        data.setEdu(education);
        //  信用卡额度
        Integer credit = ChooseEq.create()
                .when(apiApplyParameter.getCreditLimit(), "1", 1)
                .when(apiApplyParameter.getCreditLimit(), "2", 2)
                .when(apiApplyParameter.getCreditLimit(), "3", 2)
                .when(apiApplyParameter.getCreditLimit(), "4", 2)
                .when(apiApplyParameter.getCreditLimit(), "5", 2)
                .when(apiApplyParameter.getCreditLimit(), "6", 2)
                .end(1);
        data.setCredit(credit);
        //  职业
        //1：民企员工
        //2：企业主
        //3：自由职业
        //4：个体户
        //5：公务员
        //6：国企员工
        //7：事业单位员工
        //8：外企员工
        Integer career = ChooseEq.create()
                .when(apiApplyParameter.getCareer(), "1", 1)
                .when(apiApplyParameter.getCareer(), "2", 3)
                .when(apiApplyParameter.getCareer(), "3", 2)
                .when(apiApplyParameter.getCareer(), "4", 5)
                .when(apiApplyParameter.getCareer(), "5", 4)
                .end(1);
        data.setWorking(career);
        // 客户ip
        data.setJoinip(apiApplyParameter.getIp());
        AES aes = AES.createEcb(KEY.getBytes());
        String dataStr = aes.encryptToBase64Str(JsonUtils.toJson(data));

        Map<String, Object> map = MapUtils.newHashMap(newMap -> {
            newMap.put("channel", CHANNEL);
            newMap.put("timestamp", System.currentTimeMillis());
            newMap.put("bizParam", dataStr);
        });
        return JsonUtils.toJson(map);
    }

    @Override
    public RespPlatformPhoneMd5Apply respApply(String respJson) throws Exception {
        JSONObject jsonObject = JsonUtils.get(respJson);
        if (jsonObject == null) {
            return RespPlatformPhoneMd5Apply.ofFail();
        }
        if (!Eq.object(jsonObject.getInteger("code"), 200)) {
            return RespPlatformPhoneMd5Apply.ofFail();
        }
        return RespPlatformPhoneMd5Apply.ofSuc();
    }

    @Override
    public RespPlatformPhoneMd5DataExchange respDataExchange(String respJson) {
        JSONObject jsonObject = JsonUtils.get(respJson);
        if (jsonObject == null) {
            return RespPlatformPhoneMd5DataExchange.ofFail();
        }
        if (!Eq.object(jsonObject.getInteger("code"), 100)) {
            return RespPlatformPhoneMd5DataExchange.ofFail();
        }

        RespPlatformPhoneMd5DataExchange result = RespPlatformPhoneMd5DataExchange.ofSuc();

        result.setPrice(BigDecimal.valueOf(1));
        result.setLogoPath("https://ts-upload-1326563950.cos.accelerate.myqcloud.com/image_path/20250627102550A003_503e4844001d97fda3eaca12bee93c997e50f6b9.png");
        result.setDisplayName("融点通");
        result.setProductName("融点通");
        return result;
    }

    @Override
    public RespPlatformNoticeApply parseApplyNotice(RequestVO requestVO) {
        return null;
    }

    @Override
    public Map<String, Object> respApplyNotice(ApiBizStatus apiBizStatus) {
        return Map.of();
    }
}
